function ExportVolume2Tiffstack(volume,dir, no_delete_dir)
%% Write 3D volume image to stack of tiffs

% - Michael Eager (michael.eager@monash.edu)
%

if nargin < 2 || isempty(dir)
    error('saveDepth2Tiffstack error  Usage: saveDepth2Tiffstack(volume,dir)')
end
    
    
if ~isdir(dir)
    system(['mkdir -p ' dir])
end

%% Nomalise the image
max_im = max(volume(:));
min_im = min(volume(:));
if min_im ~=0 && max_im ~=1
    volume = (volume - min_im)./(max_im - min_im);
end

%% Write the images to file
for i=1:size(volume,1)
    imwrite(uint16(squeeze(volume(i,:,:))*(2^16 -1) ),[dir '/' num2str(i,'%04d') '.tiff'])    
end

%% Compress the tiff stack into a zip file
 system(['zip -r ' dir '.zip ' dir ])
 
%% Delete the directory if required 
 if nargin < 3 
     system(['rm -rf ' dir ]);
 end
 
%% test
% saveTiffstack(depth,'Depth');
